package com.hyperfix.washer.websocket;

import com.hyperfix.washer.config.ServerEncoder;
import com.hyperfix.washer.config.WebSocketConfig;
import com.hyperfix.washer.common.MonitorRegistrar;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * @author JiangChunYu
 * 2024/3/18
 */
@Slf4j
@Component
@ServerEndpoint(
        value = "/chart/{userId}",
        encoders = {ServerEncoder.class},
        subprotocols = {"protocol"},
        configurator = WebSocketConfig.class
)
public class AppWebSocket {
    private static MonitorRegistrar monitorRegistrar;

    @Resource
    public void setMonitorRegistrar(MonitorRegistrar monitorRegistrar) {
        AppWebSocket.monitorRegistrar = monitorRegistrar;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {
        monitorRegistrar.addMonitor(userId, session);
        log.info("用户{}连接， 当前连接数量: {}", userId, monitorRegistrar.currentUserNum());
    }

    @OnClose
    public void onClose(@PathParam("userId") Integer userId) {
        monitorRegistrar.removeMonitor(userId);
        log.info("用户{}断开连接， 当前连接数量: {}", userId, monitorRegistrar.currentUserNum());
    }
}
